package com.talent.jiwen.adapter;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.abc.live.ABCLiveUIHelp;
import com.abcpen.core.define.ABCConstants;
import com.abcpen.open.api.model.RoomMo;
import com.talent.jiwen.R;
import com.talent.jiwen.chatlive.InteractiveActivity;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.Member;
import com.talent.jiwen.http.result.OrderResult;
import com.talent.jiwen.ui.widgets.CourseInfoView;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.MyToast;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;

public class CourseWaitAdapter extends RecyclerView.Adapter<CourseWaitAdapter.CourseWaitViewHoler> {

    private Context context;
    private List<OrderResult.Order> dataList;
    public List<CourseWaitViewHoler> viewHolerList = new ArrayList<>();

    public CourseWaitAdapter(Context context, List<OrderResult.Order> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public CourseWaitViewHoler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_wait_course, parent, false);

        return new CourseWaitViewHoler(view);
    }

    @Override
    public void onBindViewHolder(CourseWaitViewHoler holder, final int position) {

        holder.setDataPosition(position);
        if (!(viewHolerList.contains(holder))) {
            viewHolerList.add(holder);
        }

        final OrderResult.Order data = dataList.get(position);

        ImageUtil.loadCorner4Image(context, data.getTeacherHeadImage(), holder.teacherIv);

        String subjectName = Constant.subjectMap.get(data.getSubjectId());
        String grade = "";
        if (data.getGradeLevel() >= 1 && data.getGradeLevel() <= 6 ){
            grade = "小学";
        }else if (data.getGradeLevel() > 6  && data.getGradeLevel() < 10){
            grade = "初中";
        }else{
            grade = "高中";
        }
        holder.nameTv.setText(grade + subjectName + data.getTeacherName());

        //题目详情
        CourseInfoView.CourseInfoData courseInfoData = new CourseInfoView.CourseInfoData();
        courseInfoData.setContent(data.getQuestionIntroduction());
        List<Member> memberList = new ArrayList<>();
        memberList.clear();
        memberList.addAll(data.getMemberList());
        courseInfoData.setMemberList(memberList);
        List<String> imgList = new ArrayList<>();
        if (!Validators.isEmpty(data.getQuestionImages())) {
            String[] imgs = data.getQuestionImages().split(",");
            for (int i = 0; i < imgs.length; i++) {
                imgList.add(imgs[i]);
            }
        }
        courseInfoData.setImgList(imgList);
        holder.courseInfoView.bindData(courseInfoData);

        holder.timeTv.setText(data.getChangeTime());

        //订单状态
        switch (data.getOrderStatus()) {
            case 1:
                //已接单
//                holder.statusTv.setBackgroundResource(R.drawable.bg_corner_blue);
//                holder.statusTv.setText(context.getString(R.string.wait_to_start_time));
                holder.statusIv.setImageResource(R.mipmap.iv_course_status_wait);
                holder.timeTv.setTextColor(ContextCompat.getColor(context , R.color.text_gray_9));
                holder.enterTv.setBackgroundResource(R.drawable.bg_empty_circle_gray);
                holder.enterTv.setTextColor(ContextCompat.getColor(context , R.color.text_gray_9));
                holder.enterTv.setText("取消订单");
                holder.enterTv.setEnabled(true);
                holder.enterTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        studentCancelOrder(data.getId(), position);
                    }
                });
                break;
            case 5:
                //进行中
//                holder.statusTv.setBackgroundResource(R.drawable.bg_corner_orange);
//                holder.statusTv.setText(context.getString(R.string.starting));
                holder.statusIv.setImageResource(R.mipmap.iv_course_status_start);
                holder.timeTv.setTextColor(ContextCompat.getColor(context , R.color.common_app_color));
                holder.enterTv.setBackgroundResource(R.drawable.bg_empty_circle_blue);
                holder.enterTv.setTextColor(ContextCompat.getColor(context , R.color.common_app_color));
                holder.enterTv.setText(context.getString(R.string.enter_course));
                holder.enterTv.setEnabled(true);
                holder.enterTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        joinClass(data.getId());
                    }
                });
                break;
        }

    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    /**
     * 只刷新时间
     */
    public void notifyData() {
        if (dataList.size() > viewHolerList.size() || dataList.size() == viewHolerList.size()) {
            for (int i = 0; i < viewHolerList.size(); i++) {
                viewHolerList.get(i).timeTv.setText(dataList.get(viewHolerList.get(i).position).getChangeTime());
            }
        } else {
            viewHolerList.clear();
            notifyDataSetChanged();
        }

    }

    public class CourseWaitViewHoler extends RecyclerView.ViewHolder {
        ImageView teacherIv;
        TextView nameTv;
//        TextView statusTv;
        ImageView statusIv;
        TextView timeTv;
        TextView enterTv;
        CourseInfoView courseInfoView;

        private int position;

        public void setDataPosition(int position) {
            this.position = position;
        }

        public CourseWaitViewHoler(View itemView) {
            super(itemView);

            teacherIv = (ImageView) itemView.findViewById(R.id.teacherIv);
            nameTv = (TextView) itemView.findViewById(R.id.nameTv);
//            statusTv = (TextView) itemView.findViewById(R.id.statusTv);
            statusIv = (ImageView)itemView.findViewById(R.id.statusIv);
            timeTv = (TextView) itemView.findViewById(R.id.timeTv);
            enterTv = (TextView) itemView.findViewById(R.id.enterTv);
            courseInfoView = (CourseInfoView) itemView.findViewById(R.id.courseInfoView);
        }
    }

    /**
     * 学生取消订单
     *
     * @param orderId
     */
    private void studentCancelOrder(String orderId, final int position) {
        Map<String, String> map = new HashMap<>();
        map.put("studentId", SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId", orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().studentCancelOrder(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber(context) {
            @Override
            protected void _onNext(Object o) {
                MyToast.show(context, "取消成功");
                dataList.remove(position);
                notifyDataSetChanged();
            }

            @Override
            protected void _onError(String message) {
                MyToast.show(context, message);
            }
        }, true);
    }

    /**
     * 学生进入课程
     *
     * @param roomId
     */
    private void joinClass(final String roomId) {
        Map<String, String> map = new HashMap<>();
        map.put("studentId", SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId", roomId);

        Observable observable = ApiFactory.getEducationApiSingleton().studentJoinClass(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber(context) {
            @Override
            protected void _onNext(Object o) {
                goLive(roomId);
            }

            @Override
            protected void _onError(String message) {
                MyToast.show(context, message);
            }
        }, true);
    }

    /**
     * 进入房间
     *
     * @param roomId
     */
    public void goLive(String roomId) {
        String rid = roomId;
        int liveType = 2;
//        roleType = ABCConstants.USER_OTHER;//学生
        ABCLiveUIHelp uiHelp = ABCLiveUIHelp.init()
                .setUserID(SPUtil.getBSUId())
                .setUserName(SPUtil.getUserName())
                .setIsManager(false)
                .setDefaultOpenCamera(true)
                .setDefaultOpenMic(true);

        RoomMo roomMo = new RoomMo();
        roomMo.room_id = rid;
        roomMo.name = rid;
        roomMo.live_type = liveType;

        startLiveActivity(uiHelp, roomMo);
    }


    private boolean isManager = false;
//    private boolean isRecording = true;
//    private int roleType = ABCConstants.USER_OTHER;

    /**
     * Room 基本废弃掉  可以自行更改
     *
     * @param uiHelp
     * @param roomMo
     */
    public void startLiveActivity(ABCLiveUIHelp uiHelp, RoomMo roomMo) {
        ABCLiveUIHelp abcLiveUIHelp = null;
        if(!SPUtil.booleanDataOut(SPConstant.IS_FIRST_GUIDE)){
            abcLiveUIHelp= uiHelp.setIsShowGuide(true);
            SPUtil.booleanDataIn(SPConstant.IS_FIRST_GUIDE,true);
        }else{
            abcLiveUIHelp= uiHelp.setIsShowGuide(false);
        }
        abcLiveUIHelp.setIsManager(isManager);
        roomMo.isRecord = 1;
        abcLiveUIHelp.setUserIconDefault(R.drawable.abc_default_icon);
        abcLiveUIHelp.setUserAvatarUrl(SPUtil.getUserHeadImg());
//        abcLiveUIHelp.setEndTime(System.currentTimeMillis() + 45 * 1000);
        abcLiveUIHelp.setStartTime(System.currentTimeMillis() + 10 * 1000);
        abcLiveUIHelp.setRoleType(isManager ? ABCConstants.MANAGER_TYPE : ABCConstants.NONE_TYPE);
        abcLiveUIHelp.startInteractiveLiveActivity(context, roomMo, InteractiveActivity.class);
    }
}
